package com.zyw.customcalendar;

import java.util.ArrayList;
import com.zyw.customcalendar.dao.CalendarSQLiteDao;
import com.zyw.customcalendar.model.EventModel;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class EventManager{

	private LinearLayout mEventLayout;

	private CalendarSQLiteDao mSqliteDao;

	private ArrayList<EventModel> eventlist;

	private Activity mContext;

	private String currentTime;

	public EventManager(Activity context) {
		mContext = context;
		InitView();
	}

	public void refreshView(String startTime) {
		if(currentTime != null && currentTime.equals(startTime)){
			return;
		}
		currentTime = startTime;
		InitData(startTime);
		setAdapter();
	}

	public void InitView(){
		mEventLayout = (LinearLayout) mContext.findViewById(R.id.event_layout);
	}

	public void InitData(String startTime){
		mSqliteDao = new CalendarSQLiteDao();
		eventlist = mSqliteDao.getLikeData(startTime);
		if(eventlist == null)
			eventlist = new ArrayList<>(0);
	}

	public void setAdapter(){
		int count = mEventLayout.getChildCount();
		for(int k = count - 1; k > 0; k--)
			mEventLayout.removeViewAt(k);

		for(int i = 0; i < eventlist.size(); i++){
			View itemView = LayoutInflater.from(mContext).inflate(R.layout.event_layout_item, null);

			TextView textTime = (TextView) itemView.findViewById(R.id.text_event_time);
			TextView textContent = (TextView) itemView.findViewById(R.id.text_content);
			TextView textNote = (TextView) itemView.findViewById(R.id.text_note);
			ImageView eventBtn = (ImageView) itemView.findViewById(R.id.event_next_btn);

			EventModel model = eventlist.get(i);

			int length = model.startDate.length();
			String startTime = model.startTime.substring(length);
			textTime.setText(startTime.trim());
			textContent.setText(model.content);
			if(model.noteContent == null || "".equals(model.noteContent)){
				textNote.setVisibility(View.GONE);
			}else{
				textNote.setVisibility(View.VISIBLE);
				textNote.setText(model.noteContent);
			}

			eventBtn.setTag(model);
			eventBtn.setOnClickListener(eventClickListener);

			mEventLayout.addView(itemView);
		}
	}

	private final OnClickListener eventClickListener = new OnClickListener(){
		@Override
		public void onClick(View v) {
			EventModel model = (EventModel) v.getTag();
			Intent intent = new Intent(mContext, EventActivity.class);
			intent.putExtra("event_model", model);
			android.util.Log.i("zyw","model.id="+model.id);
			mContext.startActivity(intent);
		}
	};
}
